package com.tanhua.service;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tanhua.dao.AdminMapper;
import com.tanhua.domain.Admin;
import com.tanhua.domain.AdminHolder;
import com.tanhua.exception.BusinessException;
import com.tanhua.utils.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class AdminService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private AdminMapper adminMapper;

    public ResponseEntity verification(String uuid, HttpServletResponse response) throws IOException {

        // 制作一个验证码图片
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(300, 100);
        // 获取验证码的内容 放入redis中 key:uuid value:验证码内容
        String yzm = lineCaptcha.getCode();
        stringRedisTemplate.opsForValue().set("manager_code_"+uuid,yzm,5, TimeUnit.MINUTES);
        // 写回给前端
        lineCaptcha.write(response.getOutputStream());
        return ResponseEntity.ok(null);
    }

    public ResponseEntity login(String username, String password, String verificationCode, String uuid) {
        //开发中 前端和后台都要验证
        //1 验证验证码不为空
        if(StrUtil.isEmpty(verificationCode) || StrUtil.isEmpty(uuid)){
            //抛一个自定义的异常
            throw new BusinessException("验证码不能为空");
        }
        //2 验证用户名和密码不为空
        if(StrUtil.isEmpty(username) || StrUtil.isEmpty(password)){
            //抛一个自定义的异常
            throw new BusinessException("用户名或者密码不能为空");
        }
        //3 验证码是否匹配
        String code = stringRedisTemplate.opsForValue().get("manager_code_" + uuid);
        if(!verificationCode.equals(code)){
            throw new BusinessException("验证码填写错误");
        }

        // 4 查询
        QueryWrapper<Admin> qw = new QueryWrapper<>();
        qw.eq("username",username);
        Admin admin = adminMapper.selectOne(qw);

        if(admin==null){
            throw new BusinessException("没有该用户");
        }

        //比较密码
        if(!SecureUtil.md5(password).equals(admin.getPassword())){
            throw new BusinessException("密码填写错误");
        }

        // 登录成功了
        stringRedisTemplate.delete("manager_code_"+uuid);
        //将当前用户加密成一串字符串token
        String token = JwtUtil.createToken(admin.getUsername(), "manager-tanhua");
        //当前用户对象转成json
        String admin_json = JSON.toJSONString(admin);
        //将token放入redis中
        stringRedisTemplate.opsForValue().set("manager_token_"+token,admin_json,1,TimeUnit.DAYS);
        //返回json
        Map json_map=new HashMap<String,Object>();
        json_map.put("token",token);
        return ResponseEntity.ok(json_map);

    }


    // 从redis中获取token对应的登录用户
    public Admin tokenfromUser(String token) {
        String json_admin = stringRedisTemplate.opsForValue().get("manager_token_" + token);
        Admin admin = JSON.parseObject(json_admin, Admin.class);
        return admin;
    }

    public ResponseEntity logout() {
        //根据token将当前用户做删除
        Admin admin = AdminHolder.getAdmin();
        String token = admin.getToken();
        stringRedisTemplate.delete("manager_token_" + token);
        return ResponseEntity.ok(null);
    }
}
